package com.hht;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * 模拟斗地主
 * N个线程都执行到了 await 方法处，执行 公共 动作
 */
public class CyclicBarrierDemo {

	public static void main(String[] args) {
		//斗地主需要三个人，所以这里为3
		CyclicBarrier cyclicBarrier = new CyclicBarrier(3, new Runnable() {
			
			//主线程一旦通过循环屏障，就可以执行某个动作，如通过Runnable实现的动作
			@Override
			public void run() {
				System.out.println("Game start");
			}
		});
		new Player(cyclicBarrier, "A").start();
		new Player(cyclicBarrier, "B").start();
		new Player(cyclicBarrier, "C").start();
	}
}

class Player extends Thread {
	
	private CyclicBarrier cyclicBarrier;
	
	public Player(CyclicBarrier cyclicBarrier, String name) {
		setName(name);
		this.cyclicBarrier = cyclicBarrier;
	}
	
	public void run() {
		System.out.println(getName() + " is waiting other players...");
		try {
			//每个线程在循环屏障处等待
			cyclicBarrier.await();
			System.out.println(getName() + " is waiting other players2...");
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (BrokenBarrierException e) {
			e.printStackTrace();
		}
	}
}
